import type { BaseSnapshot } from '../../systems/save';

// 保持所有接口定义不变
export interface PlayerProgressV1 extends BaseSnapshot {
  version: 1;
  initedSpiritualRoot: boolean;
}

export interface PlayerProgressV2 extends BaseSnapshot {
  version: 2;
  initedSpiritualRoot: boolean;
  killEnemies: Record<string, number>;
}

export interface PlayerProgressV3 extends BaseSnapshot {
  version: 3;
  initedSpiritualRoot: boolean;
  killEnemies: Record<string, number>;
  createdAt: number;
}

export type PlayerProgressSnapshot = PlayerProgressV3;
export type PlayerProgressSnapshotOld =
  | PlayerProgressV1
  | PlayerProgressV2
  | PlayerProgressV3;

export interface PlayerProgressState {
  realm: number;
  initedSpiritualRoot: boolean;
  studyCultivationSkills: string[];
  killEnemies: Record<string, number>;
  createdAt: number;
}

export class PlayerProgressSaveManager {
  public migrate(old: PlayerProgressSnapshotOld): PlayerProgressSnapshot {
    let current = old;
    const TARGET = 3;

    while (current.version !== TARGET) {
      current = this.upgradeOnce(current);
    }

    return current as PlayerProgressSnapshot;
  }

  private upgradeOnce(
    snapshot: PlayerProgressSnapshotOld
  ): PlayerProgressSnapshotOld {
    const currentVer = snapshot.version ?? 1;

    switch (currentVer) {
      case 1:
        return this.migrateV1toV2(snapshot as PlayerProgressV1);
      case 2:
        return this.migrateV2toV3(snapshot as PlayerProgressV2);
      default:
        throw new Error(`unknown snapshot version ${currentVer}`);
    }
  }

  private migrateV2toV3(snapshot: PlayerProgressV2): PlayerProgressV3 {
    return {
      version: 3,
      initedSpiritualRoot: snapshot.initedSpiritualRoot,
      killEnemies: snapshot.killEnemies,
      createdAt: 0,
    };
  }

  private migrateV1toV2(snapshot: PlayerProgressV1): PlayerProgressV2 {
    return {
      version: 2,
      initedSpiritualRoot: snapshot.initedSpiritualRoot,
      killEnemies: {},
    };
  }

  public save(state: PlayerProgressState): PlayerProgressSnapshot {
    return {
      version: 3,
      initedSpiritualRoot: state.initedSpiritualRoot,
      killEnemies: state.killEnemies,
      createdAt: state.createdAt,
    };
  }

  public load(
    snapshot: PlayerProgressSnapshot,
    state: PlayerProgressState
  ): void {
    state.initedSpiritualRoot = snapshot.initedSpiritualRoot;
    state.killEnemies = snapshot.killEnemies;
    state.createdAt = snapshot.createdAt;
  }
}
